#!/bin/bash

# shellcheck source=meta-facebook/recipes-fb/obmc_functions/files/fb-common-functions
source /usr/libexec/fb-common-functions

MAX_RETRY=10
RETRY_DELAY_SEC=1

remove_eid()
{
  local eid=$1
  if mapper get-service "/au/com/codeconstruct/mctp1/networks/1/endpoints/${eid}" 2>/dev/null; then
    busctl call au.com.codeconstruct.MCTP1 "/au/com/codeconstruct/mctp1/networks/1/endpoints/${eid}" au.com.codeconstruct.MCTP.Endpoint1 Remove
  fi
}

remove_frontend_nic_eid()
{
  remove_eid 90
  remove_eid 91
}

setup_eid()
{
  local mctp_intf=$1
  local mctp_eid=$2

  local cur_retry=0
  while [ $cur_retry -lt $MAX_RETRY ]
  do
     cur_retry=$((cur_retry+1))
     if busctl call au.com.codeconstruct.MCTP1 "/au/com/codeconstruct/mctp1/interfaces/${mctp_intf}" au.com.codeconstruct.MCTP.BusOwner1 AssignEndpointStatic ayy 1 0x32 "${mctp_eid}"; then
         break
     else
         echo "Set EID:${mctp_eid} at INTF:${mctp_intf} failed. Retry $cur_retry/$MAX_RETRY"
         sleep "$RETRY_DELAY_SEC"
     fi
  done

  return 0
}

setup_frontend_nic_eid()
{
  setup_eid mctpi2c10 90
  setup_eid mctpi2c15 91
}

get_numeric_sensor_by_eid()
{
  local eid=$1
  local snr_id=$2
  local pldmtool_out

  pldmtool_out="$(pldmtool platform GetSensorReading -i "$snr_id" -r 0 -m "$eid")"
  if echo "$pldmtool_out" | jq 'has("presentReading")' | grep -q true; then
    echo "$pldmtool_out" | jq '.presentReading'
    return 0
  else
    return 1
  fi
}

update_numeric_sensor_value()
{
  local eid="$1"
  local snr_id="$2"
  local snr_name="$3"
  local snr_val

  if ! snr_val="$(get_numeric_sensor_by_eid "${eid}" "${snr_id}")"; then
    echo "update_numeric_sensor_value(): pldmtool failed, eid: $eid, snr_id: $snr_id, snr_name: $snr_name"
    return 1
  fi
  busctl set-property xyz.openbmc_project.ExternalSensor "/xyz/openbmc_project/sensors/temperature/$snr_name" xyz.openbmc_project.Sensor.Value Value d "$snr_val"
}

remove_frontend_nic_eid
setup_frontend_nic_eid

while true
do
  sleep 1
  update_numeric_sensor_value 90 1 NIC0_TEMP_C
  update_numeric_sensor_value 91 1 NIC1_TEMP_C
done

exit 0
